package com.daxilong.starchen.player.service;

import android.annotation.SuppressLint;
import android.app.NotificationManager;
import android.app.Service;
import android.content.ContentResolver;
import android.content.Intent;
import android.database.Cursor;
import android.media.MediaPlayer;
import android.net.Uri;
import android.os.IBinder;
import android.os.RemoteException;
import android.provider.MediaStore;
import android.widget.Toast;

import androidx.annotation.Nullable;

import com.daxilong.starchen.player.IMediaService;
import com.daxilong.starchen.player.model.MediaItem;
import com.daxilong.starchen.player.utils.NotificationUtils;

import org.greenrobot.eventbus.EventBus;

import java.io.IOException;
import java.util.ArrayList;

public class MediaService extends Service {

    /**
     * 当播放音乐成功的时候动作
     */
    public static final String OPEN_AUDIO = "com.daxilong.audio.OPENAUDIO";

    ///顺序播放-默认的播放
    public static final int ORDER_PLAY = 1;
    ///单曲循环
    public static final int REPEAT_SINGLE = 2;
    //全部循环
    public static final int REPEAT_ALL = 3;
    private int playmode = ORDER_PLAY;
    /**
     * 音频列表
     */
    private ArrayList<MediaItem> mediaItems;
    /**
     * 当前列表的播放位置
     */
    private int position;
    private MediaItem mediaItem;
    private MediaPlayer mediaplayer;
    /**
     * 通知服务管理
     */
    private NotificationManager manager;

    private final IMediaService.Stub stub = new IMediaService.Stub() {
        final MediaService service = MediaService.this;
        @Override
        public void basicTypes(int anInt, long aLong, boolean aBoolean, float aFloat, double aDouble, String aString) throws RemoteException {
        }

        @Override
        public void openAudio(int position) throws RemoteException {
            service.openAudio(position);
        }

        @Override
        public void start() throws RemoteException {
            service.start();
        }

        @Override
        public void pause() throws RemoteException {
            service.pause();
        }

        @Override
        public void next() throws RemoteException {
            service.next();
        }

        @Override
        public void pre() throws RemoteException {
            service.pre();
        }

        @Override
        public int getPlaymode() throws RemoteException {
            return service.getPlaymode();
        }

        @Override
        public void setPlaymode(int playmode) throws RemoteException {
            service.setPlaymode(playmode);
        }

        @Override
        public int getCurrentPosition() throws RemoteException {
            return service.getCurrentPosition();
        }

        @Override
        public int getDuration() throws RemoteException {
            return service.getDuration();
        }

        @Override
        public String getName() throws RemoteException {
            return service.getName();
        }

        @Override
        public String getArtist() throws RemoteException {
            return service.getArtist();
        }

        @Override
        public void seekTo(int seekto) throws RemoteException {
            service.seekTo(seekto);
        }

        @Override
        public boolean isPlaying() throws RemoteException {
            return service.isPlaying();
        }

        @Override
        public void notifyChange(String action) throws RemoteException {
            service.notifyChange(action);
        }

        @Override
        public String getAudioPath() throws RemoteException {
            return service.getAudioPath();
        }

        @Override
        public int getAudioSessionId() throws RemoteException {
            return service.getAudioSessionId();
        }

    };


    @Override
    public void onCreate() {
        super.onCreate();
        getData();
    }

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return stub;
    }

    public void openAudio(int position){
        this.position = position;

        if(mediaItems != null && !mediaItems.isEmpty()){
            mediaItem = mediaItems.get(position);
            //把上一次或者正在播放的给释放掉
            if(mediaplayer != null){
                mediaplayer.reset();
                mediaplayer.release();
                mediaplayer = null;
            }

            try {
                mediaplayer = new MediaPlayer();
                //设置准备好的监听
                mediaplayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
                    @Override
                    public void onPrepared(MediaPlayer mp) {
                        start();
                        notifyChange(OPEN_AUDIO);
                    }
                });
                mediaplayer.setOnErrorListener(new MediaPlayer.OnErrorListener() {
                    @Override
                    public boolean onError(MediaPlayer mp, int what, int extra) {
                        return true;
                    }
                });
                mediaplayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
                    @Override
                    public void onCompletion(MediaPlayer mp) {
                        if(playmode != REPEAT_SINGLE) {
                            next();
                        }
                    }
                });
                mediaplayer.setDataSource(mediaItem.getData());
                mediaplayer.prepareAsync();//本地资源和网络资源都行
//                mediaplayer.prepare();//本地资源

                if (playmode == MediaService.REPEAT_SINGLE) {
                    mediaplayer.setLooping(true);
                } else {
                    mediaplayer.setLooping(false);
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }else{
            //数据还没有加载好
            Toast.makeText(MediaService.this, "数据还没有加载好呢！", Toast.LENGTH_SHORT).show();
        }
    }


    /**
     * 音频播放的绝对路径
     * @return
     */
    private String getAudioPath() {
        return mediaItem.getData();
    }

    @SuppressLint("MissingPermission")
    public void start() {
        mediaplayer.start();
        //弹出通知-点击的时候进入音乐播放器页面
        NotificationUtils.createNotificationChannel(this); // 先创建渠道（只需执行一次）
        NotificationUtils.showNotification(this, "熊宝音乐", "正在播放:"+getName());
    }

    public void pause() {
        mediaplayer.pause();
    }
    
    public void next() {
        position++;
        if (position > mediaItems.size() - 1) {
            position = 0;
        }
        openAudio(position);
    }

    public void pre() {
        position--;
        if(position < 0 )
            position = 0;
        openAudio(position);
    }

    /**
     * 获取播放模式
     * 单曲循环
     * 全部循环
     * @return
     */
    public int getPlaymode() {
        return playmode;
    }

    public void setPlaymode(int playmode) {
        this.playmode = playmode;

        if (playmode == MediaService.REPEAT_SINGLE) {
            mediaplayer.setLooping(true);
        } else {
            mediaplayer.setLooping(false);
        }
    }

    public int getCurrentPosition() {
        return mediaplayer.getCurrentPosition();
    }

    public int getDuration(){
        return mediaplayer.getDuration();
    }

    public String getName() {
        return mediaItem.getName();
    }

    /**
     * 演唱者
     */
    public String getArtist() {
        return mediaItem.getArtist();
    }

    public void seekTo(int seekto) {
        mediaplayer.seekTo(seekto);
    }

    private boolean isPlaying() {
        return mediaplayer.isPlaying();
    }

    private int getAudioSessionId() {
        return mediaplayer.getAudioSessionId();
    }

    /**
     * 根据不同的动作发广播
     * @param action
     */
    private void notifyChange(String action) {
        EventBus.getDefault().post(new MediaItem());
    }

    private void getData() {
        new Thread(){
            @Override
            public void run() {
                mediaItems = new ArrayList<MediaItem>();
                ContentResolver contentResolver = getContentResolver();
                Uri uri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
                String[] objects = {
                        MediaStore.Audio.Media.DISPLAY_NAME,//在Sdcard显示的名称
                        MediaStore.Audio.Media.DURATION,//视频的长度
                        MediaStore.Audio.Media.SIZE,//视频文件大小
                        MediaStore.Audio.Media.DATA,//视频的绝对地址
                        MediaStore.Audio.Media.ARTIST//艺术家
                };
                Cursor cursor =  contentResolver.query(uri, objects, null, null, null);
                if(cursor != null){
                    while (cursor.moveToNext()){

                        MediaItem mediaItem = new MediaItem();
                        String name = cursor.getString(0);
                        mediaItem.setName(name);

                        long duration = cursor.getLong(1);
                        mediaItem.setDuration(duration);

                        long size = cursor.getLong(2);
                        mediaItem.setSize(size);

                        String data = cursor.getString(3);
                        mediaItem.setData(data);

                        String artist = cursor.getString(4);
                        mediaItem.setArtist(artist);

                        //把视频添加到列表中
                        mediaItems.add(mediaItem);
                    }
                    cursor.close();;
                }
            }
        }.start();

    }

}
